<template>
  <ele-modal
    form
    :width="420"
    :model-value="modelValue"
    title="发货"
    @closed="closed"
    @update:model-value="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
      <el-form-item v-if="tableData?.length" label="打包单号" label-position="top">
        <el-table
          :data="tableData"
          size="small"
          :show-summary="tableData.length > 1"
          :summary-method="getSummaries"
        >
          <el-table-column type="index" label="序" width="45" align="left" />
          <el-table-column prop="pack_order_sn" label="打包单号" align="left" min-width="140" />
          <el-table-column prop="product_num" label="品数" align="center" />
          <el-table-column prop="num" label="商品总数" align="center" />
        </el-table>
      </el-form-item>
      <el-form-item label="物流公司" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请填写物流公司"
        />
      </el-form-item>
      <el-form-item label="物流单号" prop="number">
        <el-input
          v-model="form.number"
          placeholder="请填写物流单号"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="updateModelValue(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">确定</el-button>
    </template>
  </ele-modal>
</template>

<script setup>
const props = defineProps({
  /** 弹窗是否打开 */
  modelValue: Boolean,
  data: {
    type: Object,
    default: () => [],
  },
})

const emit = defineEmits(['done', 'update:modelValue'])

const tableData = computed(() => {
  return props.data.map((v) => {
    v.product_num = v.product_list.length
    v.num = v.product_list.reduce((acc, cur) => utils.Big(acc).plus(cur.num).toNumber(), 0)
    return v
  })
})

const formRef = ref(null)

const loading = ref(false)

/** 表单数据 */
const [form, resetFields] = utils.useFormData({
  name: '',
  number: '',
})

/** 表单验证规则 */
const rules = reactive({
  name: {
    required: true,
    message: '请填写物流公司',
    trigger: 'blur',
  },
  number: {
    required: true,
    message: '请填写物流单号',
    trigger: 'blur',
  },
})

/** 更新modelValue */
function updateModelValue(value) {
  emit('update:modelValue', value)
}

function save() {
  formRef.value?.validate?.((valid) => {
    if (!valid)
      return
    loading.value = true
    emit('done', form, () => loading.value = false)
  })
}

function closed() {
  resetFields()
  formRef.value?.clearValidate?.()
}

function getSummaries({ columns, data }) {
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const keys = ['num']
    if (keys.includes(column.property)) {
      sums[index] = data.reduce((acc, cur) => utils.Big(acc).plus(cur[column.property]).valueOf(), 0)
    }
    else {
      sums[index] = ''
    }
  })

  return sums
}
</script>

<style lang="less" scoped></style>
